<?
/**
 * Copyright 2007 Melange.
 *
 * This file is part of Melange_Framework
 *
 * PHP-HTTP is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * PHP-HTTP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PHP-HTTP; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package aas
 *
 */


/**
 * Include AuthenticatorBase
 */
require_once("AuthenticatorBase.php");


/**
 * BasicAuthenticator class
 * 
 * An <b>Authenticator</b> and <b>Valve</b> implementation of HTTP BASIC
 * Authentication, as outlined in RFC 2617:  "HTTP Authentication: Basic
 * and Digest Access Authentication."
 *
 * @category    Melange Framework
 * @package     aas
 * @copyright   Copyright (c) 2007 Jeroen Simons. All rights reserved
 * @author      Jeroen Simons <jeroen@melange.nl>
 * @link        http://www.melange.nl/
 */

class BasicAuthenticator
        extends AuthenticatorBase {

    /**
     * Logger
     *
     * @var LogCategory
     */
    protected $log;
    
    
    // ----------------------------------------------------------- Constructors    
    
    
    /**
     * Construct new Basic Authenticator.
     *
     */
    public function __construct() {
        $this->log = LoggerManager::getLogger("BasicAuthenticator");
    }
    


    // --------------------------------------------------------- Public Methods


    /**
     * Authenticate the user making this request, based on the specified
     * login configuration.  Return <code>true</code> if any specified
     * constraint has been satisfied, or <code>false</code> if we have
     * created a response challenge already.
     *
     * @param request  Request we are processing
     * @param response Response we are creating
     * @param config   Login configuration describing how authentication
     *                 should be performed
     * @return boolean
     * @throws IOException if an input/output error occurs
     */
    public function authenticate(Request $request,
                                Response &$response,
                                LoginConfig $config) {

        // Have we already authenticated someone?
        $principal = $request->getUserPrincipal();
        if (!is_null($principal)) {
            if ($this->log->isDebugEnabled())
                $this->log->debug("Already authenticated '" . $principal->getName() . "'");
            return true;
        }
        
        if((!$_SERVER['PHP_AUTH_USER'] || !$_SERVER['PHP_AUTH_USER'])
            && preg_match('/Basics+(.*)$/i', $_SERVER['REMOTE_USER'], $matches)) {
                list($name, $password) = explode(':', base64_decode($matches[1]));
                $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
                $_SERVER['PHP_AUTH_PW']   = strip_tags($password);
        }

        // Validate any credentials already included with this request
        $username = !empty($_SERVER['PHP_AUTH_USER']) ?
            $_SERVER['PHP_AUTH_USER'] : null;
        $password = !empty($_SERVER['PHP_AUTH_PW']) ?
            $_SERVER['PHP_AUTH_PW'] : null;

        if (!is_null($username) && !is_null($password)) {
            $principal = $this->context->getRealm()->authenticate($username, $password);
            if (!is_null($principal)) {
                $this->register($request, $principal, self::BASIC_METHOD,
                        $username, $password);
                return true;
            }
        }

        // Send an "unauthorized" response and an appropriate challenge
        $authenticate = "Basic realm=\"";
        if (is_null($config->getRealmName())) {
            $authenticate .= $request->getServerName();
            $authenticate .= ":";
            $authenticate .= strval($request->getServerPort());
        } else {
            $authenticate .= $config->getRealmName();
        }
        $authenticate .= "\"";
        
        // Popup http login box
        $response->setHeader("WWW-Authenticate", $authenticate);
        $response->sendError(Response::SC_UNAUTHORIZED);        
        $response->sendHeaders();
        
        // Waiting for cancelbutton ...
        // Process Cancel Button actions 
        $response->setIsCommitted(false);
        $this->context->processError();
        $response->finishResponse();
        exit();
        
    }

}
?>